﻿using AutoMapper;
using System;
using System.Collections.Generic;
using System.Text;

namespace CommonTool
{
    public class AutoMapperConfig: Profile
    {
        
    }
    public static class AutoMapperExtensions
    {
        public static TDestination MapTo<TDestination, TSource>(this TSource source)
           where TDestination : class
           where TSource : class
        {
            if (source == null) return default(TDestination);
            var config = new MapperConfiguration(cfg => cfg.CreateMap<TSource, TDestination>());
            var mapper = config.CreateMapper();
            return mapper.Map<TDestination>(source);
        }
        public static TDestination MapTo<TDestination>(this object source)
        {
            if (source == null) return default(TDestination);
            var config = new MapperConfiguration(cfg => cfg.CreateMap(source.GetType(), typeof(TDestination)));
            var mapper = config.CreateMapper();
            return mapper.Map<TDestination>(source);
        }
        public static List<TDestination> MapToList<TSource, TDestination>(this IEnumerable<TSource> source)
        {
            //IEnumerable<T> 类型需要创建元素的映射
            var config = new MapperConfiguration(cfg => cfg.CreateMap<TSource, TDestination>());
            //Mapper.Initialize(cfg => cfg.CreateMap<TSource, TDestination>());
            var mapper = config.CreateMapper();
            return mapper.Map<List<TDestination>>(source);
        }
    }
}
